from random import shuffle
# 阿里云核心SDK
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from django.core import cache
from Celerytasks.CeleryEmail import send_register_active_email
from django.shortcuts import render
from django.views.generic import View

from SchoolFleas import settings
from apps.user.models import User
from django.http import JsonResponse
import json
import re


# Create your views here.

class SendVerifyView(View):
    """验证码模块"""

    def post(self, request):
        # 对传过来的数据进行json解析
        data = json.loads(request.body)
        account = data['account']
        TypeofAccount = JudgeAccountType(account)

        # 判断类型
        # 当输入的为手机
        if TypeofAccount == 'phone':
            phone = account
            # 判断该手机号是否已经被注册
            try:
                if User.objects.get(phone=phone):
                    return JsonResponse({'success': bool(False), 'msg': "该手机号已被注册！"})
            except User.DoesNotExist:
                pass
            # 生成验证码
            check_code = shuffle_str(TypeofAccount)
            # 发送短信
            resp = send_sms(phone, check_code)
            if resp == 'OK':
                # 缓存到redis 设置5分钟过期
                cache.set(phone, check_code, 300)
                return JsonResponse({'success': bool(True), 'msg': '发送成功！'})
            else:
                return JsonResponse({'success': bool(False), 'msg': resp})
        # 当输入的为邮箱
        elif TypeofAccount == 'email':
            email = account
            try:
                if User.objects.get(email=email):
                    return JsonResponse({'success': bool(False), 'msg': "该邮箱已被注册！"})
            except User.DoesNotExist:
                pass
            # 生成验证码
            check_code = shuffle_str(TypeofAccount)
            # 异步发送邮件
            result = send_register_active_email.delay(email, check_code)
            # 发送成功返回1 失败为0   1代表发送成功数量
            if result:
                # 缓存到redis 设置5分钟过期
                cache.set(email, check_code, 300)
                return JsonResponse({'success': bool(True), 'msg': '发送成功！'})
            else:
                return JsonResponse({'success': bool(False), 'msg': "发送失败！"})
        else:
            return JsonResponse({'success': bool(False), 'msg': "账号格式有误！"})


class RegisterView(View):
    """用户注册模块"""

    def get(self, request):
        pass

    '''
        account前端传过来的数据(手机号或者邮箱号)
        password前端传过来的密码
    '''

    def post(self, request):
        # 对传过来的数据进行json解析
        data = json.loads(request.body)
        account = data['account']
        password = data['password']


# 判断注册账户的类型
def JudgeAccountType(account):
    phone = r"(^[1]([3-9])[0-9]{9}$)"
    email = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
    # 如果是手机号
    if re.match(phone, account):
        return "phone"
    elif re.match(email, account):
        return "email"
    else:
        return None


def shuffle_str(TypeofAccount):
    if TypeofAccount == 'phone':
        alphabet_str = "abcdefg0123456789"
    else:
        alphabet_str = "0123456789"

    # 将字符串转换成列表
    str_list = list(alphabet_str)
    # 调用random模块的shuffle函数打乱列表
    shuffle(str_list)
    # 将列表转字符串
    # 截取0-6位
    return ''.join(str_list[0:6])


# 短信
def send_sms(phone, checkcode):
    client = AcsClient(settings.ACCESS_KEYID, settings.ACCESS_SECRET, 'cn-hangzhou')

    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', "cn-hangzhou")
    request.add_query_param('PhoneNumbers', phone)
    # 短信签名
    request.add_query_param('SignName', settings.SMS_SIGIN)
    # 短信模板
    request.add_query_param('TemplateCode', settings.SMS_MODEL)
    request.add_query_param('TemplateParam', "{\"code\":\"%s\"}" % checkcode)

    response = client.do_action(request)
    # python2:  print(response)
    print(str(response, encoding='utf-8'))
    response = json.loads(response)
    return 'OK' if response['Message'] == "OK" else response['Message']
